package dashboard.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 文件处理工具
 * 
 * @author nianzai
 * 
 */
public class FileUtil {
	private static final Log log = LogFactory.getLog(FileUtil.class);

	/**
	 * 将内容覆盖现有文件,如果文件不存在,创建新文件,并将内容写入
	 * 
	 * @param fileName
	 * @param strContent
	 * @param encode
	 *            utf-8 gbk
	 */
	public static void writeFile(String fileName, String strContent, String encode) {
		try {
			OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(fileName), encode);
			fw.write(strContent);
			fw.flush();
			fw.close();
		} catch (Exception e) {
			log.info( "", e );
		}
	}

	/**
	 * 将内容覆盖现有文件,如果文件不存在,创建新文件,并将内容写入
	 * 
	 * @param fileName
	 * @param strContent
	 * @param encode
	 *            utf-8 gbk
	 */
	public static void writeAppendFile( String fileName, String strContent, String encode ){

		try{
			OutputStreamWriter fw = new OutputStreamWriter( new FileOutputStream( fileName, true ), encode );
			fw.write( strContent );
			fw.flush();
			fw.close();
		}
		catch( Exception e ){
			log.info( "", e );
		}
	}

	/**
	 * 读取文件全部内容
	 * 
	 * @param filename
	 *            UTF-8
	 * @return
	 */
	public static String readFile(String filename, String encode) {
		StringBuilder sb = new StringBuilder();
		try {
			FileInputStream fin = new FileInputStream(filename);
			InputStreamReader fr = new InputStreamReader(fin, encode);

			BufferedReader br = new BufferedReader(fr);// 建立BufferedReader对象，并实例化为br
			String Line = br.readLine();// 从文件读取一行字符串
			// 判断读取到的字符串是否不为空
			while (Line != null) {
				sb.append(Line);
				sb.append("\n");
				Line = br.readLine();// 从文件中继续读取一行数据
			}
			sb.deleteCharAt(sb.length() - 1);
			br.close();// 关闭BufferedReader对象
			fr.close();// 关闭文件
		} catch (Exception e) {
			log.info( "", e );
		}
		return sb.toString();
	}

//	
//	BufferedReader in = Files.newBufferedReader(Paths.get(filename), Charsets.UTF_8);
//	String line = in.readLine();
//	while ((line = in.readLine()) != null) {
//		String[] fields = line.split(LogDelimiter.TAB_SEP, -1);
//		blackIPSet.add(fields[0]);
//	}
//	IOUtils.closeQuietly(in);
//	com.google.common.io.Files.readLines(file, charset, callback)
//	FileUtils.lineIterator(filename, "UTF-8");
//	IOUtils.lineIterator(inputstream, "UTF-8");
//	CharSource charsource = Files.asCharSource(new File(filename),Charsets.UTF_8);
//	charsource.readLines(new LineProcessor<Integer>() {
//		private int lineCount=0;
//		@Override
//		public Integer getResult() {
//			return lineCount;
//		}
//		@Override
//		public boolean processLine(String line) throws IOException {
//			if(!StringUtils.isBlank(line)){
//				String[] fields = line.split(LogDelimiter.TAB_SEP, -1);
//				blackIPSet.add(fields[0]);
//			}
//			lineCount++;
//			return true;
//		}					
//	});
	
	/**
	 * 读取文件全部内容
	 * 
	 * @param fin
	 * @param encode
	 * @return
	 */
	public static String readFile(InputStream fin, String encode) {
		StringBuilder sb = new StringBuilder();
		try {
			InputStreamReader fr = new InputStreamReader(fin, encode);
			BufferedReader br = new BufferedReader(fr);// 建立BufferedReader对象，并实例化为br
			String Line = br.readLine();// 从文件读取一行字符串
			while (Line != null) {
				sb.append(Line);
				sb.append("\n");
				Line = br.readLine();// 从文件中继续读取一行数据
			}
			br.close();// 关闭BufferedReader对象
			fr.close();// 关闭文件
		} catch (Exception e) {
			log.info( "", e );
		}
		return sb.toString();
	}

	/**
	 * 将数据追加写入到文件,如果文件不存在创建文件
	 * 
	 * @param filename
	 * @param contents
	 */
	public static void appendFile(String filename, String contents) {
		try {
			RandomAccessFile rf = new RandomAccessFile(filename, "rw");// 定义一个类RandomAccessFile的对象，并实例化
			rf.seek(rf.length());// 将指针移动到文件末尾
			rf.writeUTF(contents);
			rf.close();// 关闭文件流
		} catch (Exception e) {
			log.info( "", e );
		}
	}

	/**
	 * 将数据追加写入到文件最前面,如果文件不存在创建文件
	 * 
	 * @param filename
	 * @param contents
	 */
	public static void appendFileHead(String filename, String contents) {
		try {
			RandomAccessFile rf = new RandomAccessFile(filename, "rw");// 定义一个类RandomAccessFile的对象，并实例化
			rf.seek(0);// 将指针移动到文件开始
			rf.write(contents.getBytes());
			rf.close();// 关闭文件流
		} catch (Exception e) {
			log.info( "", e );
		}
	}

	/**
	 * 向文件中写入binary
	 * 
	 * @param filename
	 * @param bytes
	 */
	public static void writeBinary(String filename, byte[] bytes) {
		try {
			RandomAccessFile rf = new RandomAccessFile(filename, "rw");
			rf.seek(0);
			rf.write(bytes);
			rf.close();
		} catch (Exception e) {
			log.info( "", e );
		}
	}

	/**
	 * 读取文件里binary
	 * 
	 * @param filename
	 * @return
	 */
	public static byte[] readBinary(String filename) {
		byte[] contents = new byte[0];
		try {
			RandomAccessFile rf = new RandomAccessFile(filename, "r");
			byte[] bytes = new byte[1024];
			rf.seek(0);
			while ((rf.read(bytes)) != -1)
				contents = FileUtil.arrayCoalition( contents, bytes );
			rf.close();
		} catch (Exception e) {
			log.info( "", e );
		}
		return contents;
	}

	/**
	 * 从文件后往前读n行
	 * 
	 * @param filename
	 * @param n
	 * @return
	 */
	public static String fromEndRFread(String filename, int n) {
		int lines = 0;
		StringBuffer sb = new StringBuffer();
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(filename, "r");
			long len = rf.length();
			long start = rf.getFilePointer();
			long nextend = start + len - 1;
			String line;
			rf.seek(nextend);
			int c = -1;
			while (nextend > start) {
				c = rf.read();
				if (c == '\n' || c == '\r') {
					if (lines > n)
						break;
					lines++;
					line = rf.readLine();
					if (line != null)
						sb.append(line + "\r\n");
					nextend--;
				}
				nextend--;
				rf.seek(nextend);
				if (nextend == 0)// 当文件指针退至文件开始处，输出第一行
					sb.append(rf.readLine());
			}
		} catch (IOException e) {
			log.info( "", e );
		} finally {
			try {
				if (rf != null)
					rf.close();
			} catch (IOException e) {
				log.info( "", e );
			}
		}
		return sb.toString();
	}

	/**
	 * 数组合并
	 * 
	 * @param a
	 *            byte[]
	 * @param b
	 *            byte[]
	 * @return
	 */
	public static byte[] arrayCoalition( byte[] a, byte[] b ){

		byte[] temp = new byte[ a.length + b.length ];
		System.arraycopy( a, 0, temp, 0, a.length );
		System.arraycopy( b, 0, temp, a.length, b.length );
		return temp;
	}

}
